package service

import (
	"fly/models"
	"fly/req"
	"fly/resp"
	"github.com/beego/beego/v2/client/orm"
	"github.com/duke-git/lancet/v2/slice"
)

type AircraftExperienceService struct {
	BaseService
	DictService SysDictService
}

func (c *AircraftExperienceService) SaveOrUpdate(aircraftId int64, experienceList []*req.ExperienceReq,
	operator int64) (err error) {
	_, err = orm.NewOrm().QueryTable(new(models.AircraftExperience)).Filter("aircraft_id", aircraftId).Delete()
	if len(experienceList) == 0 {
		return nil
	}
	o := orm.NewOrm()
	for _, experience := range experienceList {
		_, err = o.Insert(&models.AircraftExperience{
			BaseModel:        models.BaseModel{Creator: operator},
			AircraftId:       aircraftId,
			ExperienceDictId: experience.DictId,
			Count:            experience.Count,
		})
	}
	return
}

func (c *AircraftExperienceService) GetExperienceList(aircraftId int64) (ids []int64, err error) {
	var list []*models.AircraftExperience
	_, err = orm.NewOrm().QueryTable(new(models.AircraftExperience)).Filter("aircraft_id", aircraftId).All(&list, "experience_dict_id")
	if err != nil {
		return []int64{}, err
	}
	ids = slice.Map(list, func(index int, item *models.AircraftExperience) int64 {
		return item.ExperienceDictId
	})
	return ids, nil
}

func (c *AircraftExperienceService) GetSimpleExperienceList(aircraftId int64) (list []*resp.ExperienceResp, err error) {
	var experiences []*models.AircraftExperience
	_, err = orm.NewOrm().QueryTable(new(models.AircraftExperience)).Filter("aircraft_id",
		aircraftId).All(&experiences)
	if err != nil {
		return
	}
	list = slice.Map(experiences, func(index int, item *models.AircraftExperience) *resp.ExperienceResp {
		dict, _ := c.DictService.GetSimpleDictById(item.ExperienceDictId)
		ex := &resp.ExperienceResp{
			Id:         item.Id,
			AircraftId: aircraftId,
			DictId:     item.ExperienceDictId,
			Count:      item.Count,
		}
		if dict != nil {
			ex.DicCode = dict.DicCode
			ex.DicKey = dict.DicKey
			ex.DicValue = dict.DicValue
		}
		return ex
	})
	return
}
